<template>
	<view class="page">
		<u-navbar leftIconSize='30rpx'  :title="title"
			@leftClick="$utils.back()" :placeholder="true">
		</u-navbar>
		<view class="body">
			<scroll-view style="height: 100%;" :scroll-y="true">
				<u--form labelAlign='right' labelPosition="left" :model="data" ref="form" labelWidth="140rpx"
					:labelStyle="{fontSize: '26rpx',}">
					<u-form-item label="收货人：" prop="name" borderBottom>
						<u--input placeholder="请输入收货人" v-model="data.name" border="none"></u--input>
					</u-form-item>
					<u-form-item label="手机号：" prop="phone" borderBottom>
						<u-input placeholder="请输入手机号" v-model="data.phone" border="none">
							<template slot="prefix">
								<text style="font-size: 26rpx;">+86</text>
							</template>
						</u-input>
					</u-form-item>
					<u-form-item label="所属区域：" prop="area" borderBottom @click="show=true">
						<u-input placeholder="请输入省市区、乡镇" v-model="data.area" border="none" />
					</u-form-item>
					<u-form-item label="详细地址：" prop="detailed" borderBottom>
						<u-input v-model="data.detailed" placeholder="请输入详细地址例如街道，楼栋号" border="none">
							<template slot="suffix">
								<view @click='paster'>
									粘贴地址
								</view>
							</template>
						</u-input>
					</u-form-item>
					<u-form-item label="标签：" prop="tag" borderBottom>
						<view class="tagBox">
							<view class="tag" v-for="(item,index) in ['家','公司']" :key="index" @click="chooseTag(item)"
								:class="{choose:data.tag==item}">{{item}}</view>
							<view class="tag" @click="chooseTag(form.addressTag)" :class="{choose:data.tag==form.addressTag}">
								{{form.addressTag?form.addressTag:"自定义"}}
								<u-icon name="edit-pen" size="30rpx" @click="modalShow=true"></u-icon>
							</view>
						</view>
					</u-form-item>
					<u-form-item label="是否默认：" prop="default" borderBottom>
						<u-switch v-model="data.default" @change="change"></u-switch>
					</u-form-item>
				</u--form>
			</scroll-view>
		</view>
		<view>

			<u-popup :round="10" :show="show" @close="close">
				<view class="popup">
					<view class="popupTitle">
						<u-icon name="close" color='#fff'></u-icon>
						<text style="font-size: 26rpx;font-weight: 400;">请选择所在地区</text>
						<u-icon name="close" @click="close"></u-icon>
					</view>
					<u-tabs :inactiveStyle='{fontSize:"26rpx"}' :activeStyle='{fontSize:"26rpx"}'
						:itemStyle="{fontSize:'26rpx',height: '88rpx'}" :list="list" @click="chooseTabs"
						scrollable="false" :current="current" lineColor="#f56c6c"></u-tabs>
					<view style="margin: 40rpx 0rpx;font-size: 26rpx;" v-if="rrovinceId">
						<text @click="num=1">
							{{rrovinceName}}
						</text>
						<text @click="num=2" style="margin-left: 40rpx;" v-if="cityId">
							{{cityName}}
						</text>
						<text @click="num=3" style="margin-left: 40rpx;" v-if="districtsId">
							{{districtsName}}
						</text>
						<text @click="num=4" style="margin-left: 40rpx;" v-if='streetsId'>
							{{streetsName}}
						</text>
					</view>
					<scroll-view scroll-y="true" style="height: 60vh;">
						<view v-for="item in arr" :key="item">
							<view v-if="com_area.filter(item3=>item3.first==item).length">
								<view style="font-size: 26rpx;">
									{{item.toUpperCase()}}
								</view>
								<u-line></u-line>
								<view @click="choose_fun(item2)"
									:class="{chooseRrovince:item2.id==rrovinceId||item2.id==cityId||item2.id==districtsId||item2.id==streetsId}"
									style="padding: 20rpx 40rpx;display: flex;align-items: center;"
									v-for="item2 in com_area.filter(item3=>item3.first==item)" :key="item2.id">
									<view
										v-show="item2.id==rrovinceId||item2.id==cityId||item2.id==districtsId||item2.id==streetsId">
										<u-icon name="checkmark" color="red" size="48rpx"></u-icon>
									</view>
									{{item2.name}}
								</view>
							</view>
						</view>

						<view class="arrBox">
							<view v-for="item in arr" :key="item"
								v-if="com_area.filter(item3=>item3.first==item).length">
								{{item.toUpperCase()}}
							</view>
						</view>

					</scroll-view>
				</view>
			</u-popup>
			<u-modal :show="modalShow" :showCancelButton='true' @close='cancel' @cancel='cancel' @confirm='update'>
				<view style="width: 100%;">
					<view class="popupTitle">
						<u-icon name='close' color='#fff' />
						<view>
							编辑标签
						</view>
						<u-icon name='close' @click='cancel' />
					</view>
					<view style="padding: 0 40rpx;">
						<u--form labelWidth='100' labelPosition="top" :model="form" :rules="formRules" ref="uForm">
							<u-form-item label="标签:" prop="addressTag" borderBottom>
								<u--input v-model="form.addressTag" placeholder="请输入内容" />
							</u-form-item>
						</u--form>
					</view>
				</view>
			</u-modal>
		</view>
		<view class="footer">
			<u-button :disabled='disabled' type="primary" :text="title" @click="sumbit" shape="circle"></u-button>
		</view>
	</view>
</template>

<script>
	import {
		pinyin
	} from 'pinyin-pro';
	import {
		AddressParse
	} from '../lib/addressParseBundle.js';
	export default {
		onLoad(op) {
			this.title = op.type
			this.opId = op.id
			this.jump=op.jump
			if (op.type == '新增地址') return
			this.$api.address.detail(op.id).then(res => {
				this.data = {
					name: res.data.address.name,
					phone: res.data.address.phone,
					area: res.data.address.address_district,
					detailed: res.data.address.address_detail,
					tag: res.data.address.address_tag,
					default: res.data.address.is_default ? true : false,
				}
				this.rrovinceName = res.data.address.province
				this.cityName = res.data.address.city
				this.districtsName = res.data.address.district
				this.streetsName = res.data.address.street
			})

		},
		computed: {
			com_area() {
				switch (this.num) {
					case 1:
						switch (this.current) {
							case 0:
								return this.continent;
								break;
							case 1:
								return this.overseas;
								break;
						};
						breaK;
					case 2:
						switch (this.current) {
							case 0:
								return this.city;
								break;
							case 1:
								return [];
								break;
						};
						break;
					case 3:
						switch (this.current) {
							case 0:
								return this.districts;
								break;
							case 1:
								return [];
								break;
						};
						break;
					case 4:
						switch (this.current) {
							case 0:
								return this.streets;
								break;
							case 1:
								return [];
								break;
						};
						break;
				}
			}
		},
		data() {
			return {
				jump:null,
				formRules: {
					'addressTag': {
						type: 'string',
						required: true,
						message: '请输入内容',
						trigger: ['blur', 'change']
					},
				},
				modalShow: false,
				form: {
					addressTag: uni.getStorageSync('addressTag')
				},
				disabled: false,
				opId: '',
				title: '',
				rrovinceName: '',
				cityName: '',
				num: 1,
				rrovinceId: null,
				current: 0,
				show: false,
				data: {
					name: '',
					phone: '',
					area: '',
					detailed: '',
					tag: "",
					default: true,
				},
				rules: {
					'phone': [{
							type: 'string',
							required: true,
							message: '请填写手机号',
							trigger: ['blur', 'change']
						},
						{
							// 自定义验证函数，见上说明
							validator: (rule, value, callback) => {
								return uni.$u.test.mobile(value);
							},
							message: '请输入正确手机号',
							// 触发器可以同时用blur和change
							trigger: ['change', 'blur'],
						}
					],
					'name': [{
						type: 'string',
						required: true,
						message: '请填写收货人',
						trigger: ['blur', 'change']
					}],
					'area': [{
						type: 'string',
						required: true,
						message: '请填写地址',
						trigger: ['blur', 'change']
					}],
					'detailed': [{
						type: 'string',
						required: true,
						message: '请填写详细地址',
						trigger: ['blur', 'change']
					}]

				},
				list: [{
					name: '中国大陆',
				}, {
					name: '港澳台及海外',
				}],
				continent: [],
				overseas: [],
				arr: [
					'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
					'u', 'v', 'w', 'x', 'y', 'z'
				],
				city: [],
				cityId: '',
				districts: [],
				districtsId: '',
				districtsName: '',
				streets: [],
				streetsId: '',
				streetsName: ''
			}
		},
		onReady() {

			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
			this.$refs.form.setRules(this.rules)
		},
		mounted() {
			this.getRrovince()
		},
		methods: {
			update(){
				this.$refs.uForm.validate().then(res => {
					uni.setStorageSync('addressTag', this.form.addressTag);
					this.modalShow = false
				}).catch(errors => {
					uni.$u.toast('校验失败')
				})
				
			},
			cancel() {
				this.$refs.uForm.resetFields()
				this.modalShow = false
				this.form.addressTag=uni.getStorageSync('addressTag')
			},
			paster() {
				uni.getClipboardData({
					success: (res) => {
						const address = res.data
						const result = AddressParse.parse(address)
						if (result && result.length) {
							let html = ''
							for (let key in result[0]) {
								if (result[0][key]) {
									html += key + `:` + result[0][key] + `<br/>`
								}
							}
							const data = result[0]
							this.rrovinceName = data.province
							this.cityName = data.city
							this.districtsName = data.area
							this.data.area = this.rrovinceName + this.cityName + this.districtsName + this
								.streetsName
							this.data.name = data.name
							if (data.phone) {
								this.data.phone = data.phone
							} else {
								this.data.phone = data.mobile
							}
							console.log(data)
							console.log(this.rrovinceName, this.cityName, this.districtsName, this.streetsName)
							console.log(this.data.area)

						}
						this.data.detailed = res.data
					}
				});
			},
			change(e) {
				this.data.default = e
			},
			sumbit() {
				this.$refs.form.validate().then(res => {
					
						this.disabled = true
					if (this.title == '修改地址') {
						this.updata()
					} else {
						this.add()
					}
				}).catch(errors => {
					uni.$u.toast('请填写完整信息')
				})
			},
			chooseTag(item) {
				this.data.tag = item
			},
			chooseTabs(item) {
				this.current = item.index
			},
			async getRrovince() {

				const {
					pinyin
				} = require('pinyin-pro');
				const res = await this.$api.address.getRrovince()
				if (res) {
					const arr = ['港澳', '台湾', '钓鱼岛', '澳门']
					this.overseas = res.data.provinces.sort((a, b) => a.name.localeCompare(b.name, 'zh')).filter(
						item => arr.includes(item.name)).map(item => {
						return {
							...item,
							first: pinyin(item.name.substr(0, 1), {
								pattern: 'first',
								toneType: 'none'
							}),
							type: 'rrovince'
						}
					})
					this.continent = res.data.provinces.sort((a, b) => a.name.localeCompare(b.name, 'zh')).filter(
						item => !arr.includes(item.name)).map(item => {
						return {
							...item,
							first: pinyin(item.name.substr(0, 1), {
								pattern: 'first',
								toneType: 'none'
							}),
							type: 'rrovince'
						}
					})
				}

			},
			choose_fun(item) {
				if (item.type == 'rrovince') {
					this.num = 2
					this.rrovinceId = item.id
					this.rrovinceName = item.name
					this.getCity(item.id)
				} else if (item.type == 'city') {
					this.num = 3
					this.cityId = item.id
					this.cityName = item.name
					this.getDistricts(item.id)
				} else if (item.type == 'districts') {
					this.num = 4
					this.districtsId = item.id
					this.districtsName = item.name
					this.getStreets(item.id)
				} else {
					this.streetsId = item.id
					this.streetsName = item.name
				}

			},
			async getCity(id) {
				this.cityName = ""
				this.districtsName = ''
				this.streetsName = ''
				const res = await this.$api.address.getCity({
					provinceId: id
				})
				if (res) {
					this.city = res.data.cities.sort((a, b) => a.name.localeCompare(b.name, 'zh')).map(item => {
						return {
							...item,
							first: pinyin(item.name.substr(0, 1), {
								pattern: 'first',
								toneType: 'none'
							}),
							type: 'city'
						}
					})
				}
			},
			async getDistricts(id) {
				this.districtsName = ''
				this.streetsName = ''
				const res = await this.$api.address.getDistricts({
					cityId: id
				})
				if (res) {
					this.districts = res.data.districts.sort((a, b) => a.name.localeCompare(b.name, 'zh')).map(
						item => {
							return {
								...item,
								first: pinyin(item.name.substr(0, 1), {
									pattern: 'first',
									toneType: 'none'
								}),
								type: 'districts'
							}
						})
				}
			},
			async getStreets(id) {
				this.streetsName = ''
				const res = await this.$api.address.getStreets({
					districtId: id
				})
				if (res) {
					this.streets = res.data.streets.sort((a, b) => a.name.localeCompare(b.name, 'zh')).map(item => {
						return {
							...item,
							first: pinyin(item.name.substr(0, 1), {
								pattern: 'first',
								toneType: 'none'
							}),
							type: 'streets'
						}
					})
				}
			},
			close() {

				this.show = false
				this.data.area = this.rrovinceName + this.cityName + this.districtsName + this.streetsName
			},
			add() {
				const {
					name,
					phone,
					area,
					detailed,
					tag
				} = this.data
				this.$api.address.add({
					name,
					phone,
					address_district: area,
					address_detail: detailed,
					province: this.rrovinceName,
					city: this.cityName,
					district: this.districtsName,
					street: this.streetsName,
					is_default: this.data.default ? 1 : 0,
					address_tag: tag
				}).then(res => {
					uni.$u.toast('插入地址成功')
					if(this.jump){
						setTimeout(() => {
							uni.redirectTo({
								url: '/product/selectAddress'
							})
						}, 500)
						return
					}
					setTimeout(() => {
						uni.redirectTo({
							url: '/address/AddressBookPage/AddressBookPage'
						})
					}, 500)
				}).catch(err => {
					this.disabled = false
					uni.$u.toast(err.data.message)
				})
			},
			updata() {
				const {
					name,
					phone,
					area,
					detailed,
					tag,
				} = this.data
				this.$api.address.put(this.opId, {
					name,
					phone,
					address_district: area,
					address_detail: detailed,
					province: this.rrovinceName,
					city: this.cityName,
					district: this.districtsName,
					street: this.streetsName,
					is_default: this.data.default ? 1 : 0,
					address_tag: tag
				}).then(res => {
					uni.$u.toast('编辑地址成功')
					if(this.jump){
						setTimeout(() => {
							uni.redirectTo({
								url: '/product/selectAddress'
							})
						}, 500)
						return
					}
					setTimeout(() => {
						uni.redirectTo({
							url: '/address/AddressBookPage/AddressBookPage'
						})
					}, 500)
				}).catch(err => {
					this.disabled = false
					uni.$u.toast(err.data.message)
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	::v-deep .u-navbar {
		>view:last-child {
			box-shadow: 0 2rpx 2rpx rgba($color: #000000, $alpha: 0.1);
		}
	}

	.chooseRrovince {
		font-weight: 600;

	}

	.arrBox {
		z-index: 5;
		top: 500rpx;
		right: 50rpx;
		position: fixed;
		width: 5%;
		text-align: center;
		font-size: 26rpx;
		background-color: #d5d5d5;
		border-radius: 50rpx;

		view {
			border-bottom: 1rpx solid #f5f5f5;
		}

		view:last-child {
			border: none;
		}

	}



	.popup {
		width: 100%;
		box-sizing: border-box;
		padding: 20rpx 40rpx 0;
		font-size: 26rpx;
	}

	.footer {
		height: 80rpx;
	}

	.tagBox {
		display: flex;
		flex-wrap: wrap;
	}

	.tag {
		display: flex;
		align-items: center;
		padding: 5rpx 20rpx;
		background-color: #fff;
		border: 1rpx solid #ddd;
		border-radius: 50rpx;
		margin-right: 10rpx;
		font-size: 26rpx;
		color: #010101;
		margin-bottom: 10rpx;
	}

	.choose {
		border: 1rpx solid #0000d3;
	}

	.page {
		padding: 0rpx 20rpx;
		height: 100vh;
		padding-bottom: calc(constant(safe-area-inset-bottom) + 10rpx);
		/* 兼容 iOS 设备 */
		padding-bottom: calc(env(safe-area-inset-bottom) + 10rpx);
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
	}

	.body {
		flex: 1;
		overflow: hidden;
	}
</style>